<?php
/**
 * 活动管理
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-03-28
 * Time: 下午 11:26
 */
namespace App;

use Model\ActivityAdminMod;
use Model\ActivityCouponMod;
use Model\ActivityMemberMod;
use Model\ActivityMemberTreasureMod;
use Model\ActivityMod;
use Model\ActivityTreasureMod;
use Model\BrowseMod;
use Model\SponsorCouponMod;
use Pub\cache\Cache;
use Pub\date\Date;
use Pub\tool\Tool;
use Pub\wx\KeywordReply;

class Activity extends Action
{
	private $Activity = null;  //活动
	private $ActivityTreasure = null;  //活动的宝藏
	private $MemberTreasure = null;  //会员打开的宝藏
	private $ActivityMember = null;  //活动会员
	private $ActivityAdmin = null;
	private $ActivityCoupon = null;  //活动卡券
    private $SponsorCoupon = null;  //活动举办方投放的卡券

	public function __construct()
	{
		parent::__construct();
		$this->Activity = new ActivityMod();
	}

	/**
	 * 添加活动
	 */
	public function add()
	{
        $this->_gpc['data']['uniacid'] = $this->_uniacid;
        if($this->Activity->insert($this->_gpc['data'])){
            $this->_result = array('status'=>'success','data'=>pdo_insertid());
        }
		$this->result($this->_result);
	}

	/**
	 * 修改活动
	 */
	public function edit()
	{
	    Cache::remove(Cache::ACTIVITY_INFO,array('activity_id'=>$this->_gpc['activity_id']));
        $this->changeResponKeyword();
		if($this->Activity->update($this->_gpc['data'],array('id'=>$this->_gpc['activity_id']))){
            $this->_result = array('status'=>'success');
        }
		$this->result($this->_result);
	}

    /**
     * 更改活动响应关键词
     */
	private function changeResponKeyword()
    {
        if($this->_gpc['data']['response_keyword'] != $this->_gpc['original_response_keyword']){
            $KeywordReply = new KeywordReply($this->_gpc['data']['response_keyword']);
            if(($this->_gpc['data']['response_keyword'] != '')){
                if($KeywordReply->testRepeat()){
                    $this->_result = array('status'=>'error','err_status'=>9,'err_msg'=>'活动响应关键词重复，请重新设置');
                    $this->result($this->_result);
                }
                $KeywordReply->add();
            }
            $KeywordReply->_keyword = $this->_gpc['original_response_keyword'];
            $KeywordReply->remove();
        }
    }

    /**
     * 返回指定字段的活动数据
     * @param activity_id 活动id
     * @param return 需要返回的字段
     */
	public function easyFind()
    {
        $_return = array();
        if(isset($this->_gpc['return'])) $_return = $this->_gpc['return'];
        $_activity = $this->Activity->findOne(array('id'=>$this->_gpc['activity_id'],'status !='=>9),$_return);
        if($_activity){
            if(isset($_activity['explain'])) $_activity['explain'] = htmlspecialchars_decode($_activity['explain']);
            if(isset($_activity['start'])) $_activity['start'] = date('Y-m-d H:i',$_activity['start']);
            if(isset($_activity['end'])) $_activity['end'] = date('Y-m-d H:i',$_activity['end']);
            $this->_result = array('status'=>'success','data'=>$_activity);
        }
        $this->result($this->_result);
    }


    /**
     * 审核活动更改活动状态
     * @param activity_id 活动id
     */
	public function checkActivity()
    {
        $_activity = $this->Activity->findOne(array('id'=>$this->_gpc['activity_id']),array('name','cover','shop_model'));
        //验证活动名称
        if($_activity['name'] == ''){
            $this->_result = array('status'=>'error','err_status'=>9,'err_msg'=>'活动名未设置，请前往活动后台完善活动信息');
            $this->result($this->_result);
        }
        //验证活动封面
        if($_activity['cover'] == ''){
            $this->_result = array('status'=>'error','err_status'=>8,'err_msg'=>'未设置活动封面，请前往活动后台完善活动信息');
            $this->result($this->_result);
        }
        //活动有没有投放宝藏
        $this->ActivityTreasure = new ActivityTreasureMod();
        $_treasure = $this->ActivityTreasure->findOne(array('activity_id'=>$this->_gpc['activity_id']),array('id'));
        if(!$_treasure && $_activity['shop_model'] == 1){
            $this->ActivityCoupon = new ActivityCouponMod();
            $_treasure = $this->ActivityCoupon->findOne(array('activity_id'=>$this->_gpc['activity_id'],'goal'=>1),array('id'));
        }
        $this->SponsorCoupon = new SponsorCouponMod();
        $_sponsor_coupon = $this->SponsorCoupon->findOne(array("activity_id"=>$this->_gpc["activity_id"]),array("id"));
        if(!$_treasure && !$_sponsor_coupon){
            $this->_result = array('status'=>'error','err_status'=>7,'err_msg'=>'活动未投放奖励，请前往活动后台投放奖励');
            $this->result($this->_result);
        }
        if($this->Activity->update(array('status'=>1),array('id'=>$this->_gpc['activity_id']))){
            $this->_result = array('status'=>'success');
        }else{
            $this->_result = array('status'=>'error','err_status'=>0,'err_msg'=>'操作失败');
        }
        $this->result($this->_result);
    }

	/**
	 * 修改活动的实体宝藏*****************************
	 */
	public function editEntity()
	{
		if(count($this->_gpc['entity_list']) > 0){
			$this->ActivityTreasure = new ActivityTreasureMod();
			$_entity_id = array();
			foreach($this->_gpc['entity_list'] as $_v){
				unset($_v['icon_url']);
				if(isset($_v['id'])){
					$_entity_id[] = $_v['id'];
					$this->ActivityTreasure->update($_v,array('id'=>$_v['id']));
				}else{
					$_v['activity_id'] = $this->_gpc['activity_id'];
					$this->ActivityTreasure->insert($_v);
					$_entity_id[] = pdo_insertid();
				}
			}
			$_delete = $this->ActivityTreasure->findDeleteTreasure($this->_gpc['activity_id'],2,$_entity_id);
			if(count($_delete) > 0){
				foreach($_delete as $_v){
					$this->ActivityTreasure->update(array('status'=>0),array('id'=>$_v['id']));
				}
			}
			$this->_result = array('status'=>'success');
			$this->result($this->_result);
		}else{
			$this->_result = array('status'=>'success');
			$this->result($this->_result);
		}
	}

	/**
	 * 修改活动的虚拟宝藏
	 */
	public function editBz()
	{
		if(count($this->_gpc['activity_bz']) > 0){
			$this->ActivityTreasure = new ActivityTreasureMod();
			$_entity_id = array();
			foreach($this->_gpc['activity_bz'] as $_v){
				unset($_v['icon_url']);
				if(isset($_v['id'])){
					$_entity_id[] = $_v['id'];
					$this->ActivityTreasure->update($_v,array('id'=>$_v['id']));
				}else{
					$_v['activity_id'] = $this->_gpc['activity_id'];
					$this->ActivityTreasure->insert($_v);
					$_entity_id[] = pdo_insertid();
				}
			}
			$_delete = $this->ActivityTreasure->findDeleteTreasure($this->_gpc['activity_id'],1,$_entity_id);
			if(count($_delete) > 0){
				foreach($_delete as $_v){
					$this->ActivityTreasure->update(array('status'=>0),array('id'=>$_v['id']));
				}
			}
			$this->_result = array('status'=>'success');
			$this->result($this->_result);
		}else{
			$this->_result = array('status'=>'success');
			$this->result($this->_result);
		}
	}

	/**
	 * 删除活动
	 */
	public function delete()
	{
		$_result = $this->Activity->update(array('status' => 9), array('id' => $this->_gpc['activity_id']));
		if ($_result) $this->_result = array('status' => 'success');
		$this->result($this->_result);
	}

	/**
	 * 后台获取指定数据总数
	 * status
	 */
	public function total()
	{
		$_where = array('uniacid' => $this->_uniacid, 'status !=' => 9);
		if(isset($this->_gpc['search_keyword'])){
            if($this->_gpc['search_type'] == 'id'){
                $_where['id'] = $this->_gpc['search_keyword'];
            }else if($this->_gpc['search_type'] == 'name'){
                $_where['name like'] = '%'.$this->_gpc['search_keyword'].'%';
            }else{
                $_where['address like'] = '%'.$this->_gpc['search_keyword'].'%';
            }
        }
        if ($this->_gpc['status'] == 1) {
            $_where['start >'] = TIMESTAMP;
        } else if ($this->_gpc['status'] == 2) {
            $_where['start <='] = TIMESTAMP;
            $_where['end >'] = TIMESTAMP;
        } else {
            $_where['end <'] = TIMESTAMP;
        }
		$this->result(array('status' => 'success', 'data' => $this->Activity->total($_where)));
	}

	/**
	 * 获取活动列表
	 * limit
	 * status
	 */
	public function li()
	{
		$_where = array('uniacid'=>$this->_uniacid,'status'=>$this->_gpc['status']);
        if(isset($this->_gpc['search_keyword'])){
            if($this->_gpc['search_type'] == 'id'){
                $_where['id'] = $this->_gpc['search_keyword'];
            }else if($this->_gpc['search_type'] == 'name'){
                $_where['name like'] = '%'.$this->_gpc['search_keyword'].'%';
            }else{
                $_where['address like'] = '%'.$this->_gpc['search_keyword'].'%';
            }
        }
		if ($this->_gpc['status_phases'] == 1) {
			$_where['start >'] = TIMESTAMP;
		} else if ($this->_gpc['status_phases'] == 2) {
			$_where['start <='] = TIMESTAMP;
			$_where['end >'] = TIMESTAMP;
		} else if($this->_gpc['status_phases'] == 3) {
			$_where['end <'] = TIMESTAMP;
		}
		$_list = $this->Activity->findAll($_where, array('limit' => $this->_gpc['limit'], 'order' => array('start', 'asc')), array('id', 'name', 'response_keyword', 'start', 'end', 'address'));
		if (count($_list) > 0) {
			foreach ($_list as $_k => $_v) {
				$_list[$_k]['start'] = date('Y-m-d H:i', $_v['start']);
				$_list[$_k]['end'] = date('Y-m-d H:i', $_v['end']);
				$_invest = $this->activityInvest($_v['id']);
                $_list[$_k]['invest'] = $_invest['invest'];
                $_list[$_k]['expend'] = $_invest['expend'];
			}
			$this->_result = array('status' => 'success', 'data' => $_list);
		}
		$this->result($this->_result);
	}

    /**
     * 活动的投入资金
     * @param $_activity_id 活动id
     * @return Array 返回活动的投入资金和已消耗资金
     */
	private function activityInvest($_activity_id)
    {
        $_invest = array('invest'=>'0.00','expend'=>'0.00');
        if(!$this->ActivityTreasure instanceof ActivityTreasureMod) $this->ActivityTreasure = new ActivityTreasureMod();
        $_activity_treasure = $this->ActivityTreasure->findAll(array('activity_id'=>$_activity_id,'type'=>1),array('order'=>array('id','desc')),array('money','number','give_number'));
        if(count($_activity_treasure) > 0){
            $_invest = 0;
            $_expend = 0;
            foreach($_activity_treasure as $_v){
                $_invest += $_v['money'] * $_v['number'];
                $_expend += $_v['money'] * $_v['give_number'];
            }
            $_invest = array('invest'=>$this->makeMoney($_invest),'expend'=>$this->makeMoney($_expend));
        }
        return $_invest;
    }

	/**
	 * 通过活动id验证活动是否存在
	 */
	public function find()
	{
		$_result = $this->Activity->findOne(array('uniacid' => $this->_uniacid, 'status !=' => 9, 'id' => $this->_gpc['activity_id']), array('address','map_coords','start','end','shop_model','status'));
		if ($_result) {
			$_result['start_date'] = date('Y/m/d', $_result['start']);
			$_result['start_time'] = date('H:i', $_result['start']);
			$_result['end_date'] = date('Y/m/d', $_result['end']);
			$_result['end_time'] = date('H:i', $_result['end']);
			$_result['map_coords'] = json_decode(htmlspecialchars_decode($_result['map_coords']), true);
			$_result['phases_status'] = Date::time2time($_result['start'], $_result['end']);   //活动阶段状态
			$this->_result = array('status' => 'success', 'data' => $_result);
		} else {
			$this->_result = array('status' => 'error','err_status' => 0,'err_msg'=>'活动不存在');
		}
		$this->result($this->_result);
	}

	/**
	 * 主办方首页基础信息，活动基础信息
	 */
	public function activityInfo()
	{
		$_activity = $this->Activity->findOne(array('id'=>$this->_gpc['activity_id']),array('name','response_keyword','start','end','address','status'));
		if($_activity){
			$_activity['url'] = murl('entry//index',array('m'=>'kuyuan_vbz','activity_id'=>$this->_gpc['activity_id'],'share_uid'=>0,'route'=>urlencode('#/activity/'.$this->_gpc['activity_id'].'/0')),true,true);
			$_activity['qrcode'] = $this->getQrcode('activity_qrcode',$this->_gpc['activity_id'],$_activity['url']);
			if($_activity['status'] == 2){
                $_activity['status'] = 0;
            }else{
                $_activity['status'] = Date::time2time($_activity['start'],$_activity['end']);  //活动状态
            }
			$_activity['start_date'] = date('Y-m-d',$_activity['start']);
            $_activity['end_date'] = date('Y-m-d',$_activity['end']);
			$_activity['start'] = date('Y-m-d H:i:s',$_activity['start']);
			$_activity['end'] = date('Y-m-d H:i:s',$_activity['end']);
            $_invest = $this->activityInvest($this->_gpc['activity_id']);
            $_activity['invest'] = $_invest['invest'];
            $_activity['expend'] = $_invest['expend'];
			$_activity['surplus'] = $this->makeMoney($_activity['invest'] - $_activity['expend']);
			$this->ActivityMember = new ActivityMemberMod();
			$_activity['member_total'] = $this->ActivityMember->total(array('activity_id'=>$this->_gpc['activity_id']));
			$this->MemberTreasure = new ActivityMemberTreasureMod();
			$_activity['join_member_total'] = $this->MemberTreasure->joinMemberTotal($this->_gpc['activity_id']);
			$this->_result = array('status'=>'success','data'=>$_activity);
		}
		$this->result($this->_result);
	}

    /**
     * 获取活动的二维码
     * @return mixed|void
     */
	public function findQrcode()
    {
        $_url = murl('entry//index',array('m'=>'kuyuan_vbz','activity_id'=>$this->_gpc['activity_id'],'share_uid'=>0,'route'=>urlencode('#/activity/'.$this->_gpc['activity_id'].'/0')),true,true);
        $_qrcode = $this->getQrcode('activity_qrcode',$this->_gpc['activity_id'],$_url,true);
        if($_qrcode) $this->_result = array('status'=>'success','data'=>$_qrcode);
        $this->result($this->_result);
    }

	/**
	 * 活动名称
	 */
	public function name()
	{
		$_activity = $this->Activity->findOne(array('id' => $this->_gpc['activity_id']), array('name'));
		if ($_activity) $this->_result = array('status' => 'success', 'data' => $_activity['name']);
		$this->result($this->_result);
	}

	/**
	 * 活动会员总数
	 */
	public function memberTotal()
	{
		$this->ActivityMember = new ActivityMemberMod();
		$_total = $this->ActivityMember->total(array('activity_id'=>$this->_gpc['activity_id']));
		$this->_result = array('status'=>'success','data'=>$_total);
		$this->result($this->_result);
	}

	/**
	 * 会员列表
	 */
	public function memberList()
	{
		$this->ActivityMember = new ActivityMemberMod();
		$_list = $this->ActivityMember->findAll(array('activity_id'=>$this->_gpc['activity_id']),array('order'=>array('uid','desc'),'limit'=>$this->_gpc['limit']),array('uid'));
		if(count($_list) > 0){
			foreach($_list as $_k=>$_v){
			    $_member = $this->uidToInfo($_v['uid']);
			    $_list[$_k]['name'] = $_member['nickname'];
			    $_list[$_k]['header'] = $_member['avatar'];
				$_list[$_k]['balance'] = $this->balance($_v['uid']);
			}
			$this->_result = array('status'=>'success','data'=>$_list);
		}
		$this->result($this->_result);
	}

	/**
	 * 用户余额
	 * @param $_uid
	 */
	private function balance($_uid)
	{
		$this->MemberTreasure = new ActivityMemberTreasureMod();
		$_member_treasure = $this->MemberTreasure->findAll(array('uid'=>$_uid,'activity_id'=>$this->_gpc['activity_id'],'type'=>1),array('order'=>array('id','desc')),array('number','treasure_id','id'));
		if($_member_treasure){
			$_balance = 0;
			$this->ActivityTreasure = new ActivityTreasureMod();
			foreach($_member_treasure as $_k=>$_v){
				$_treasure = $this->ActivityTreasure->findOne(array('id'=>$_v['treasure_id']),array('money'));
				$_balance += $_treasure['money'] * $_v['number'];
			}
			return $this->makeMoney($_balance);
		}else{
			return '0.00';
		}
	}

	/**
	 * 指定会员的得到宝藏
	 */
	public function memberTreasure()
	{
		$this->MemberTreasure = new ActivityMemberTreasureMod();
		$this->ActivityTreasure = new ActivityTreasureMod();
		$_treasure = $this->MemberTreasure->findAll(array('uid'=>$this->_gpc['uid'],'activity_id'=>$this->_gpc['activity_id'],'type'=>$this->_gpc['type']),array('order'=>array('id','asc')),array('treasure_id','number'));
		if(count($_treasure) > 0){
			foreach($_treasure as $_k=>$_v){
				$_bz = $this->ActivityTreasure->findOne(array('id'=>$_v['treasure_id']),array('name','icon','money'));
				$_treasure[$_k]['name'] = $_bz['name'];
				$_treasure[$_k]['money'] = $_bz['money'];
				$_treasure[$_k]['icon'] = tomedia($_bz['icon']);
			}
			$this->_result = array('status'=>'success','data'=>$_treasure);
		}
		$this->result($this->_result);
	}

	/**
	 * 将一个数字转为金钱数字
	 * @param $_number
	 * @return float|string
	 */
	private function makeMoney($_number)
	{
		if(ceil($_number) == $_number){
			return $_number.'.00';
		}else{
			$_numArr = explode('.',$_number);
			$_decimals = end($_numArr);
			if(strlen($_decimals) == 1){
				return $_numArr[0].'.'.$_decimals.'0';
			}else if(strlen($_decimals) == 2){
				return $_number;
			}else{
				return round($_number,2);
			}
		}
	}

	/**
	 * 活动的宝藏列表
	 */
	public function treasure()
	{
		$this->ActivityTreasure = new ActivityTreasureMod();
		$_treasure = $this->ActivityTreasure->findAll(array('activity_id'=>$this->_gpc['activity_id'],'type'=>$this->_gpc['type'],'status'=>1),array('order'=>array('id','asc'),'limit'=>$this->_gpc['limit']),array('name','id','icon','number','money'));
		if(count($_treasure) > 0){
			$this->MemberTreasure = new ActivityMemberTreasureMod();
			foreach($_treasure as $_k=>$_v){
				if($this->_gpc['type'] == 1 && $_v['number'] == 0){
					$_treasure[$_k]['number'] = '不限量';
				}
				$_treasure[$_k]['give_number'] = $this->MemberTreasure->sum(array('activity_id'=>$this->_gpc['activity_id'],'treasure_id'=>$_v['id'],'type'=>$this->_gpc['type']),'number');
				$_treasure[$_k]['icon'] = tomedia($_v['icon']);
			}
			$this->_result = array('status'=>'success','data'=>$_treasure);
		}
		$this->result($this->_result);
	}

	/**
	 * 活动宝藏列表的总数
	 */
	public function treasureTotal()
	{
		$this->ActivityTreasure = new ActivityTreasureMod();
		$_total = $this->ActivityTreasure->total(array('activity_id'=>$this->_gpc['activity_id'],'type'=>$this->_gpc['type'],'status'=>1));
		$this->_result = array('status'=>'success','data'=>$_total);
		$this->result($this->_result);
	}

	/**
	 * 设置后台活动的管理账号密码
	 */
	public function setAdmin()
	{
		$this->ActivityAdmin = new ActivityAdminMod();
		$_account = $this->ActivityAdmin->findOne(array('activity_id'=>$this->_gpc['activity_id']),array('id'));
		if($_account){
			if($this->editAdmin()){
				$this->_result = array('status'=>'success');
			}else{
				$this->_result = array('status'=>'error','err_status'=>7,'err_msg'=>'设置失败');
			}
			$this->result($this->_result);
		}else{
			if($this->addAdmin()){
				$this->_result = array('status'=>'success');
			}else{
				$this->_result = array('status'=>'error','err_status'=>9,'err_msg'=>'设置失败');
			}
			$this->result($this->_result);
		}
	}

	/**
	 * 新增活动的后台管理账号
	 */
	private function addAdmin()
	{
		if($this->ActivityAdmin->findOne(array('account'=>$this->_gpc['account']),array('id'))){
			$this->_result = array('status'=>'error','err_status'=>8,'err_msg'=>'账号已存在');
			$this->result($this->_result);
		}
		$_salt = Tool::createCode();
		return $this->ActivityAdmin->insert(array(
			'uniacid'=>$this->_uniacid,
			'activity_id'=>$this->_gpc['activity_id'],
			'account'=>$this->_gpc['account'],
			'salt'=>$_salt,
			'password'=>sha1($this->_gpc['password'].$_salt)
		));
	}

	/**
	 * 修改活动的后台管理账号
	 */
	private function editAdmin()
	{
		if($this->ActivityAdmin->findOne(array('account'=>$this->_gpc['account'],'activity_id !='=>$this->_gpc['activity_id']),array('id'))){
			$this->_result = array('status'=>'error','err_status'=>8,'err_msg'=>'账号已存在');
			$this->result($this->_result);
		}
		$_salt = Tool::createCode();
		return $this->ActivityAdmin->update(array(
			'account'=>$this->_gpc['account'],
			'salt'=>$_salt,
			'password'=>sha1($this->_gpc['password'].$_salt)
		),array('activity_id'=>$this->_gpc['activity_id']));
	}

	/**
	 * 获取活动后台管理账号
	 */
	public function findAdmin()
	{
		$this->ActivityAdmin = new ActivityAdminMod();
		$_account = $this->ActivityAdmin->findOne(array('activity_id'=>$this->_gpc['activity_id']),array('account'));
		if($_account){
			$this->_result = array('status'=>'success','data'=>$_account);
		}
		$this->result($this->_result);
	}

}